import { computed, defineComponent, inject, ref, watchEffect } from "vue";
import type { CascaderStore } from "./store";
import { CascaderContextKey } from ".";
import Checkbox from "../../inner/Checkbox";
import Loading from "../../inner/Loading";
import { FeatherChevronRight } from "cui-vue-icons/feather";

export const Item = defineComponent({
    name: 'CascaderItem',
    props: {
        data: {type: Object},
        store: {type: Object},
        trigger: {type: String},
    },
    setup (props: any) {
        const store: CascaderStore = props.store;
        const valueField = store.valueField || 'value';
        const titleField = store.titleField || 'title';
        const selected = computed(() => {
            return (store.selectedKey.value?.includes(props.data[valueField]));
        });
        const classList = computed(() => ({
            'cm-cascader-item': true,
            'cm-cascader-item-active': selected.value,
            'cm-cascader-item-disabled': props.data.disabled
        }));
        const ctx: any = inject(CascaderContextKey, {});
        const loading = ref(false);
        const onClick = async () => {
            if (props.data.disabled) {
                return;
            }
            if (props.data.loading && ctx && ctx.loadData) {
                try {
                    loading.value = true;
                    await store.loadData(props.data, ctx.loadData);
                } catch (e) {
                // todo
                } finally {
                    loading.value = false;
                }
            }
            if (props.trigger === 'click') {
                store.selectItem(props.data[valueField]);
            }
            ctx && ctx.onSelect(props.data);
        };

        let timer: any = null;
        const onMouseEnter = () => {
            if (props.data.disabled) {
                return;
            }
            timer && clearTimeout(timer);
            timer = setTimeout(() => {
                !selected.value && store.selectItem(props.data[valueField]);
            }, 100);
        };

        const onCheckChange = (checked: boolean) => {
            store.checkNode(props.data[valueField], checked);
        };

        return () => <div class={classList.value} onClick={onClick}
            onMouseenter={props.trigger === 'hover' ? onMouseEnter : undefined}>
            {props.data.icon}
            {ctx.multi && props.data.checkable !== false ? <Checkbox disabled={props.data.disabled} checked={props.data.checked} onChange={onCheckChange}/> : null}
            <span class="cm-cascader-text">{props.data[titleField]}</span>
            {
                (props.data.children && props.data.children.length) || props.data.loading
                    ? (loading.value ? <Loading color="#1890ff"/> : <FeatherChevronRight class="cm-menu-submenu-cert"/>)
                    : null
            }
        </div>;
    }
});
